﻿using Application.Users.Interfaces;
using Application.Users.Models;
using MediatR;
using Shared.Exceptions;
using Shared.Http.APIResult;
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Application.Users.Commands.UpdateUser
{

    public record UpdateUserCommand(IList<UpdateUserModel> User) : IRequest<OperationResult<List<Guid>>>;

    public record UpdateUserModel
    {
        public Guid Id { get; init; }

        public string? UserName { get; init; }

        public string? PhoneNumber { get; init; }

        public string? CollegeName { get; init; }

        public string? MajorName { get; init; }
    }

    public class UpdateUserCommandHandler(IUserWriteRepository writeRepo): IRequestHandler<UpdateUserCommand, OperationResult<List<Guid>>>
    {
        public async Task<OperationResult<List<Guid>>> Handle(UpdateUserCommand request, CancellationToken ct)
        {
            OperationResult<List<Guid>> result = new()
            {
                Data = [],
                Errors = []
            };

            foreach (var user in request.User)
            {
                try
                {
                    var updatedId = await writeRepo.UpdateAsync(user, ct);
                    result.Data.Add(updatedId);
                }
                catch(DomainException ex)
                {
                    result.Errors.Add(new ()
                    {
                        Id = user.Id,
                        Message = $"{ex.ErrorCode}_{ex.Message}"
                    });
                }
                catch(InfrastructureException ex)
                {
                    //记录日志
                    result.Errors.Add(new ()
                    {
                        Id = user.Id,
                        Message = $"{ex.ErrorCode}_{ex.Message}"
                    });
                }
                catch(Exception)
                {
                    result.Errors.Add(new()
                    {
                        Id = user.Id,
                        Message = $"服务器内部错误"
                    });
                }
            }
            return result;
        }
    }
}
